package com.kaitian.demo.demo_boot_starter.aop;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kaitian.demo.demo_boot_starter.annotation.LogAnnotation;
import com.kaitian.demo.demo_boot_starter.utils.IPUtil;
import com.mongodb.util.JSON;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ：xietian
 * @version ：V1.0
 * @program ：demo
 * @date ：Created in 2022/4/14 11:53
 * @description ：日志记录
 */
@Slf4j
@Aspect
@Order
@Component
public class LogAspects {

    private ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 根据注解开始切
     */
    @Pointcut("@annotation(com.kaitian.demo.demo_boot_starter.annotation.LogAnnotation)")
    public void pointcut() { }

    /**
     * 环绕通知
     */
    @Around(value = "pointcut()")
    public Object doAfter(ProceedingJoinPoint point) {
        // 获取请求信息
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = servletRequestAttributes.getRequest();

        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        long beginTime = System.currentTimeMillis();
        //保存日志
        LogAnnotation logAnnotation = method.getAnnotation(LogAnnotation.class);
        log.info("=====================log start================================");
//        log.info("ip:{}", IPUtil.getIpAddr(request));
        log.debug("url:{}", request.getRequestURL().toString());
//        log.info("module:{}", logAnnotation.module());
//        log.info("operation:{}", logAnnotation.operator());

        //请求的方法名
        String className = point.getTarget().getClass().getName();
        String methodName = signature.getName();
        log.debug("method:{}", className + "." + methodName + "()");

        //请求的参数
        Object[] args = point.getArgs();
        if (null != args && args.length > 0) {
            List<String> params = new ArrayList<>();
            for (Object arg : args) {
                try {
                    params.add(objectMapper.writeValueAsString(arg));
                } catch (JsonProcessingException e) {
                    log.debug("params exception:{}", e.getMessage());
                    params.add(arg.getClass().getSimpleName() + "类型参数暂不记录");
                }
            }
            log.info("params:{}", params);
        }

        //执行方法
        Object result = null;
        try {
            result = point.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                log.debug("result:{}", objectMapper.writeValueAsString(result));
            } catch (JsonProcessingException e) {
                log.debug("result exception:{}", e.getMessage());
            }

            //执行时长(毫秒)
            log.debug("excute time : {} ms", System.currentTimeMillis() - beginTime);
            log.info("=====================log end================================");
        }
        return result;
    }
}